package com.yqs.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.yqs.model.entity.AirQualityIndex;
import com.yqs.model.entity.District;
import com.yqs.model.service.AirService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Ye QS
 * @version 0.1
 * @className IndexController
 * @description
 * @date 2024/8/14 17:17
 * @since jdk11
 */
@Controller
public class AirController {
    @Autowired
    private AirService airService;


    @RequestMapping(value = "/getAllAir", produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public Map<String, Object> getAllAir(@RequestParam(value = "page", defaultValue = "1") int page,
                                         @RequestParam(value = "size", defaultValue = "5") int size) {
        PageHelper.startPage(page, size); // 分页插件的启动方法
        List<AirQualityIndex> allAir = airService.getAllAir();

        PageInfo<AirQualityIndex> pageInfo = new PageInfo<>(allAir);
        Map<String, Object> result = new HashMap<>();
        result.put("success", true);
        result.put("data", pageInfo);
        return result;
    }

    @PostMapping("/addAirQuality")
    public ResponseEntity<String> addAirQuality(@RequestBody AirQualityIndex airQualityIndex) {
        try {
            District district = new District();
            district.setId(airQualityIndex.getDistrict().getId());

            // 获取当前时间并格式化为字符串
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
            String formattedDate = dateFormat.format(new Date());

            // 创建新的 AirQualityIndex 对象
            AirQualityIndex airQualityIndex1 = new AirQualityIndex(null,
                    district,
                    airQualityIndex.getMonitorTime(),
                    airQualityIndex.getPm10(),
                    airQualityIndex.getPm2_5(),
                    airQualityIndex.getMonitoringStation(),
                    formattedDate);

            // 保存到数据库
            airService.insert(airQualityIndex1);

            return ResponseEntity.ok("空气质量信息添加成功！");
        } catch (Exception e) {
            return ResponseEntity.status(500).body("添加空气质量信息失败: " + e.getMessage());
        }
    }
    @GetMapping("/airQuality1")
    public ModelAndView getAirQualityPage() {
        return new ModelAndView("airQuality"); // 这里假设您有一个名为 airQuality 的视图文件
    }
}
